<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" :before-close="handlePasswordClose" draggable>
    <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100">
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input v-model="passwordForm.currentPassword" placeholder="请输入当前密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" placeholder="请输入新密码"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handlePasswordClose">取消</el-button>
        <el-button type="primary" @click="handlePasswordConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { changePasswordApi } from "@/api/modules/business";
import { LOGIN_URL } from "@/config";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";

const router = useRouter();
const userStore = useUserStore();
const tabStore = useTabsStore();
const dialogVisible = ref(false);
const passwordFormRef = ref<any>();
const passwordForm = ref({ currentPassword: "", newPassword: "" });
const passwordRules = {
  currentPassword: { required: true, message: "请输入当前密码", trigger: "blur" },
  newPassword: { required: true, message: "请输入新密码", trigger: "blur" }
};
const openDialog = () => {
  dialogVisible.value = true;
};

function handlePasswordClose() {
  dialogVisible.value = false;
  passwordFormRef.value.resetFields();
  passwordForm.value = { currentPassword: "", newPassword: "" };
}

function handlePasswordConfirm() {
  passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (passwordForm.value.currentPassword === passwordForm.value.newPassword) return ElMessage.warning("新旧密码不能一致");
      const data = await changePasswordApi({ ...passwordForm.value });
      if (!data.result) return ElMessage.error(data.message);

      ElMessage.success(data.message + "，请重新登录");
      handlePasswordClose();
      // 清除 Token
      userStore.setToken("");
      userStore.setUserInfo({ name: "" });
      await tabStore.setTabs([]);

      // 重定向到登陆页
      await router.replace(LOGIN_URL);
    }
  });
}

defineExpose({ openDialog });
</script>
